using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class ShootController : MonoBehaviour, ISceneController, IUserAction
{
    public GameObject Crossbow; // 弓弩
    public Animator CrossbowAnim;
    public bool isFire;
    public bool isHolding;
    public CCShootManager shootManager;
    public ShootFactory factory;
    public GameObject main_camera;
    public ScoreController scoreController;
    public GameObject target1, target2, target3, target4; // 4种靶子
    public GameObject arrow; // 射出去的箭
    public string message = "";
    public int arrow_num = 0;
    private List<GameObject> arrows = new List<GameObject>(); // 箭的队列
    private List<GameObject> flyed = new List<GameObject>(); // 飞出去的箭的队列
    public float longPressDuration = 2.0f;
    private bool isLongPressing = false; // 是否正在长按
    private float pressTime = 0f;
    public int state = 0; // 0-普通状态，1-拉弓状态，2-蓄力状态
    public float power = 0f;
    public Material sky;

    GameObject LoadTarget(string name, int score, Vector3 pos, bool ifRotate) {
        GameObject target = GameObject.Instantiate(Resources.Load("Prefabs/" + name, typeof(GameObject))) as GameObject;
        if (target == null) {
            Debug.LogError("Failed to load prefab: " + name);
            return null;
        }
        target.transform.position = pos;
        if (ifRotate)
        {
            target.transform.rotation = Quaternion.Euler(90, 0, 33);
        }
        target.AddComponent<TargetController>();
        target.GetComponent<TargetController>().RingScore = score;
        Debug.Log("Target instantiated at position: " + pos + " with score: " + score);
        return target;
    }

    public void LoadResources() {
        main_camera = transform.GetChild(0).GetChild(0).gameObject;
        // Crossbow = transform.GetChild(1).gameObject;
        // 加载靶子
        for (int i = 0; i < 3; i++) {
            target1 = LoadTarget("target1", 3, new Vector3(-15 - i * 2, 1.5f, 3 - i), true);
            target1 = LoadTarget("target1", 3, new Vector3(-3 + i * 3, 1.5f, 9), false);
        }
        for (int i = 0; i < 2; i++) {
            target2 = LoadTarget("target2", 2, new Vector3(-19 + i * 2, 2.5f + i * 0.2f, 2.5f + i), true);
            target2 = LoadTarget("target2", 2, new Vector3(-1.5f + i * 3, 2.5f, 10), false);
        }
        target3 = LoadTarget("target3", 12, new Vector3(10, 4, 13), false);
        target3.AddComponent<FallController>();
        target3.tag = "target3";
        target3.transform.rotation = Quaternion.Euler(90, 0, 0);
        for (int i = 0; i < 3; i++) {
            Transform child = target3.transform.GetChild(i);
            child.gameObject.AddComponent<TargetController>();
            child.gameObject.GetComponent<TargetController>().RingScore = 12 + i;
            child.gameObject.AddComponent<FallController>();
            child.tag = "target3";
        }
        target4 = LoadTarget("targetQuick", 18, new Vector3(5, 5, -10), false);
        target4.AddComponent<FallController>();
        target4.tag = "target4";
        target4.transform.rotation = Quaternion.Euler(90, 0, 0);
        for (int i = 0; i < 2; i++) {
            Transform child = target4.transform.GetChild(i);
            child.gameObject.AddComponent<TargetController>();
            child.gameObject.GetComponent<TargetController>().RingScore = 18 + i * 2;
            child.gameObject.AddComponent<FallController>();
            child.tag = "target4";
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        // Crossbow = GetComponent<GameObject>();
        Crossbow = transform.GetChild(0).GetChild(0).GetChild(1).gameObject;
        transform.GetChild(0).GetChild(0).GetChild(1).GetChild(4).gameObject.SetActive(false);
        CrossbowAnim = Crossbow.GetComponent<Animator>();
        isFire = true;
        isHolding = true;
        SSDirector director = SSDirector.getInstance();
        director.currentSceneController = this;
        director.currentSceneController.LoadResources();
        gameObject.AddComponent<ShootFactory>();
        gameObject.AddComponent<ScoreController>();
        // gameObject.AddComponent<UserGUI>(); 
        factory = Singleton<ShootFactory>.Instance;
        scoreController = Singleton<ScoreController>.Instance;
        shootManager = Crossbow.AddComponent<CCShootManager>() as CCShootManager;
    }

    // Update is called once per frame
    void Update()
    {
        Shoot();
        HitGround();
        for (int i = 0; i < flyed.Count; i++) {
            GameObject arr = flyed[i];
            if (flyed.Count > 12 || arr.transform.position.y < -10) {
                flyed.RemoveAt(i);
                factory.RecycleArrow(arr);
            }
        }
        if (Input.GetKeyDown(KeyCode.R)) {
            LoadArrow();
            message = "弓箭填充完毕";
        }
        // if (Input.GetKeyDown(KeyCode.Q) && target3 == null) {
        //     LoadTarget3();
        // }
        // if (Input.GetKeyDown(KeyCode.E) && target4 == null) {
        //     LoadTarget4();
        // }
        if (Input.GetKeyDown(KeyCode.Alpha1)) {
            sky = Resources.Load<Material>("Skyboxes/Day6");
            RenderSettings.skybox = sky;
        }
        if (Input.GetKeyDown(KeyCode.Alpha2)) {
            sky = Resources.Load<Material>("Skyboxes/Night3");
            RenderSettings.skybox = sky;
        }
        if (Input.GetKeyDown(KeyCode.Alpha3)) {
            sky = Resources.Load<Material>("Skyboxes/Sunset1");
            RenderSettings.skybox = sky;
        }
    }

    public void Shoot() {
        if (arrows.Count > 0)
        {
            if (Input.GetMouseButtonDown(0) && state == 0)
            {
                message = "";
                transform.GetChild(0).GetChild(0).GetChild(1).GetChild(4).gameObject.SetActive(true);
                isLongPressing = true;
                CrossbowAnim.SetTrigger("pull");
                pressTime = Time.time;
                state = 1;
            }
            if (Input.GetMouseButtonUp(0) && state == 1) // 左键抬起
            {
                isLongPressing = false;
                float duration = Time.time - pressTime;
                if (duration < longPressDuration) power = duration / 2;
                else power = 1.0f;
                CrossbowAnim.SetFloat("power", power);
                CrossbowAnim.SetTrigger("hold");
                state = 2;
            }
            if (isLongPressing && Time.time - pressTime > longPressDuration) // 长按但是未抬起，且持续时间超过设定值
            {
                // 长按操作
                isLongPressing = false;
                power = 1.0f;
                CrossbowAnim.SetFloat("power", power);
                CrossbowAnim.SetTrigger("hold");
            }
            if (Input.GetButtonDown("Fire2") && state==2){ // 鼠标右键，攻击2
                transform.GetChild(0).GetChild(0).GetChild(1).GetChild(4).gameObject.SetActive(false); // 设置动作中的箭不可见
                CrossbowAnim.SetTrigger("shoot");
                arrow = arrows[0];
                arrow.SetActive(true);
                flyed.Add(arrow);
                arrows.RemoveAt(0);
                shootManager.ShootArrow(arrow, main_camera.transform.forward, power);
                CrossbowAnim.SetFloat("power", 1.0f); // 恢复力度
                arrow_num -= 1;
                state = 0;
            }
        }
        else message = "请按R装载弓箭";
    }

    public void HitGround() { // 是否射中地面
        RaycastHit hit;
        if (arrow != null && Physics.Raycast(arrow.transform.position, Vector3.down, out hit, 0.2f)) {
            if (hit.collider.gameObject.name == "Terrain") {
                arrow.tag = "ground";
                arrow.GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0); // 速度设为0
                arrow.GetComponent<Rigidbody>().isKinematic = true;
            }
        }
    }

    public void LoadArrow() { // 装载箭
        arrow_num = 12;
        while (arrows.Count != 0) {
            factory.RecycleArrow(arrows[0]);
            arrows.RemoveAt(0);
        }
        for (int i = 0; i < arrow_num; i++) {
            GameObject arr = factory.GetArrow();
            arrows.Add(arr);
        }
    }

    public void LoadTarget3() {
        target3 = LoadTarget("target3", 12, new Vector3(10, 4, 13), false);
        target3.AddComponent<FallController>();
        target3.tag = "target3";
        target3.transform.rotation = Quaternion.Euler(90, 0, 0);
        for (int i = 0; i < 3; i++) {
            Transform child = target3.transform.GetChild(i);
            child.gameObject.AddComponent<TargetController>();
            child.gameObject.GetComponent<TargetController>().RingScore = 12 + i;
            child.gameObject.AddComponent<FallController>();
            child.tag = "target3";
        }
    }

    public void LoadTarget4() {
        target4 = LoadTarget("targetQuick", 18, new Vector3(5, 5, -10), false);
        target4.AddComponent<FallController>();
        target4.tag = "target4";
        target4.transform.rotation = Quaternion.Euler(90, 0, 0);
        for (int i = 0; i < 2; i++) {
            Transform child = target4.transform.GetChild(i);
            child.gameObject.AddComponent<TargetController>();
            child.gameObject.GetComponent<TargetController>().RingScore = 18 + i * 2;
            child.gameObject.AddComponent<FallController>();
            child.tag = "target4";
        }
    }

    public int GetScore() {
        return scoreController.score;
    }

    public int GetArrowNum() {
        return arrow_num;
    }

    public string GetMessage() {
        return message;
    }
}
